package main

import (
	"config-client-v1/controller/admin"
	"config-client-v1/init/global"
	j_log "config-client-v1/init/j-log"
	j_redis "config-client-v1/init/j-redis"
	"config-client-v1/middleware"
	"config-client-v1/model"
	"config-client-v1/routers"
	"config-client-v1/utils/tools"
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
)

func main() {
	defer tools.Pause()
	defer func() {
		r := recover()
		if r != nil {
			fmt.Println("panic main(): ", r)
		}
	}()
	j_redis.Start()  // 启动redis
	go model.WSRun() // 启动 websocket server
	httpRun()
}

func httpRun() {
	appMode := global.AppConfig.Section("").Key("app_mode").String()
	appPort := global.AppConfig.Section("").Key("http_port").String()
	var r *gin.Engine
	if appMode == "production" {
		gin.SetMode(gin.ReleaseMode)
		// 设置全局日志中间件
		r = gin.New()
		r.Use(middleware.LoggerToFile())
		r.Use(middleware.CustomRecovery())
	} else {
		r = gin.Default()
	}
	r.Use(routers.Cors())
	routers.GinConfigure(r) // 路由配置
	r.GET("/", func(context *gin.Context) {
		context.String(200, "http server is running on "+appPort)
	})
	r.Any("/ping", admin.DebugController{}.Ping)
	routers.AdminRouterInit(r) // 设计端路由
	routers.ApiRouterInit(r)   // 测试端路由
	j_log.LogInfo([]interface{}{"http listen on :" + appPort})
	err := r.Run(":" + appPort) // 监听http server
	if err != nil {
		log.Fatal(err.Error())
	}
}
